﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cafe.Web.Models;
using Cafe.Model;
using Data.Mobile;
using System.Data;
using MobileCafe.Models;
using System.Globalization;
namespace MobileCafe.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Mobiles/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Login(string User,string Pwd, string ID1, string ID2, int Remember)
        {
            if (Remember == 1)
            {
                HttpCookie cookie = new HttpCookie("UserCafe");
                cookie.Value = User + "|" + ID1 + "|" + ID2;
                cookie.Expires = DateTime.Now.AddYears(1);
                Response.Cookies.Add(cookie);
            }
            else
            {
                HttpCookie cookie = new HttpCookie("UserCafe");
                cookie.Value = User + "|" + ID1 + "|" + ID2;
                cookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(cookie);
            
            }
            ConnectModel model = new ConnectModel();
            bool check = false;
            try
            {
                using (Cafe.Model.vinas_2013dbEntities db = Cafe.Model.DbEnt.GetEntities)
                {
                    var sys = db.SystemCustomers.Where(m => m.UniqueCode == (ID1 + ID2)).FirstOrDefault();
                    if (sys != null)
                    {
                        model.Pwd = sys.Password;
                        model.UserName = sys.UsName;
                        model.Database = sys.DbName;
                        model.Ip = sys.Ip;
                        model.UniqueCode = sys.UniqueCode;

                    }
                    else if ((ID1 + ID2)=="00000000")
                    { model.UniqueCode = (ID1 + ID2); check = true; }

                }
                if(!check)
                    using (mData db = new mData(new SelectDate(DateType.Day, DateTime.Now, DateTime.Now), model.Ip, model.Database, model.UserName, model.Pwd))
                    {
                         check = db.LoginValid(User,Util.ToString(Pwd), "");
                    
                    }
                
                if (check)
                {
                    Session["UserCafe"] = model;
                    return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
                }
                else
                    return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
            }
            catch(Exception ex)
            {
                WriteError(ex.Message, (ID1 + ID2));
                return Json(new { Success = false }, JsonRequestBehavior.AllowGet);

            }
        }

        
        public JsonResult Logout()
        {
            Session["UserCafe"] = null;
            return Json(new { Success = true, }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetReport()
        {
            ConnectModel model=new ConnectModel();
            if (Session["UserCafe"] != null)
                model = (ConnectModel)Session["UserCafe"];

            DataTable dt = new DataTable(), dt_qty = new DataTable(), dt_cost = new DataTable();
            bool cost_detail = true;

            SelectDate _date = null;
            if (Session["DateSelected"] != null)
                _date = (SelectDate)Session["DateSelected"];
            else
                _date = new SelectDate(DateType.Day, DateTime.Now, DateTime.Now);
            if(model.UniqueCode=="00000000")//id data demo
            {

                dt.ReadXml(Server.MapPath("/App_Data/Pvs.xml"));
                dt_cost.ReadXml(Server.MapPath("/App_Data/dtcost.xml"));
                dt_qty.ReadXml(Server.MapPath("/App_Data/dtqty.xml"));
            }
            else
            {
             using (mData db = new mData(_date, model.Ip, model.Database, model.UserName, model.Pwd))
             {
                dt = db.ProfitAndRevenue();
                dt_qty = db.Qty();
                dt_cost = db.Cost(ref cost_detail);
             }
            }
            DataModel models = new DataModel();

            if (dt != null)
            {
                models.Pvs = dt.AsEnumerable().Select(m => new PVModel() { GroupName = m["Tennhom"].ToString(), Profit = Util.ToDecimal(m["Tongtien"]), Revenue = Util.ToDecimal(m["LoiNhuan"]), Name = m["Tenhang"].ToString(), Unit = m["Tendvt"].ToString() }).OrderBy(m => m.GroupName).ToList();

            }
            if(dt_qty!=null)
                models.Quantitys = dt_qty.AsEnumerable().Select(m => new QuantityModel() { GroupName = m["Tennhom"].ToString(), Qty = Util.ToDecimal(m["SoLuong"]), Name = m["Tenhang"].ToString(), Unit = m["Tendvt"].ToString() }).OrderBy(m => m.GroupName).ToList();
            if (dt_cost != null)
            {
                models.Costs = dt_cost.AsEnumerable().Select(m => new CostModel()
                {
                    Date = Convert.ToDateTime(m["Ngay"]).ToString("dd/MM/yyyy"),
                    Descr = Util.ToString(m["DienGiai"]),
                    TypeDescr = (cost_detail) ? Util.ToString(m["TenLoai"]) : "",
                    Money = Util.ToDecimal(m["SoTien"]),
                    IsDetail = Util.ToInt(cost_detail)
                }).ToList();
            }
            //write xml data
        //    dt.WriteXml(Server.MapPath("/App_Data/Pvs.xml"),XmlWriteMode.WriteSchema,true);
        //    dt_cost.WriteXml(Server.MapPath("/App_Data/dtcost.xml"), XmlWriteMode.WriteSchema, true);
        //    dt_qty.WriteXml(Server.MapPath("/App_Data/dtqty.xml"), XmlWriteMode.WriteSchema, true);
            return Json(new { Success = true, data = models }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult LoginStatus()
        {
            if(object.Equals(Session["UserCafe"],null))
                return Json(new { Success = false }, JsonRequestBehavior.AllowGet);

            return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult OptionsChanged(string optype, string opfrom, string opto)
        {
            SelectDate _ops = null;
            switch (optype)
            {
                case "day": _ops = new SelectDate(DateType.Day, DateTime.Now, DateTime.Now); break;
                case "week": _ops = new SelectDate(DateType.Week, DateTime.Now, DateTime.Now); break;
                case "month":
                    if (!string.IsNullOrEmpty(opfrom) && opfrom.Length > 0)
                    {
                        string[] arr = opfrom.Split('/');
                        DateTime from = new DateTime(Util.ToInt(arr[1]), Util.ToInt(arr[0]), 1);
                        _ops = new SelectDate(DateType.Month, from, from);
                    }
                    break;
                case "year":
                    if (!string.IsNullOrEmpty(opfrom) && opfrom.Length > 0)
                    {
                        DateTime _dt = new DateTime(Util.ToInt(opfrom), 1, 1);
                        _ops = new SelectDate(DateType.Year, _dt, _dt);
                    }
                    break;
                case "fromto":
                    DateTime _fr = DateTime.Now;
                    DateTime _to = DateTime.Now;
                    if (!string.IsNullOrEmpty(opfrom) && opfrom.Length > 0)
                    {
                        string[] arr = opfrom.Split('/');
                        _fr = new DateTime(Util.ToInt(arr[2]), Util.ToInt(arr[1]), Util.ToInt(arr[0]));
                    }
                    if (!string.IsNullOrEmpty(opto) && opto.Length > 0)
                    {
                        string[] arr = opto.Split('/');
                        _to = new DateTime(Util.ToInt(arr[2]), Util.ToInt(arr[1]), Util.ToInt(arr[0]));
                    }
                    _ops = new SelectDate(DateType.FromTo, _fr, _to);
                    break;
            }

            Session["DateSelected"] = _ops;

            return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
        }

        public  void WriteError(string errorMessage,string ID)
        {
            string Path = "~/App_Data/";
            try
            {
                
                ConnectModel model = new ConnectModel();
                if (Session["UserCafe"] != null)
                    model = (ConnectModel)Session["UserCafe"];
                string path = Path + DateTime.Today.Month + "_" + DateTime.Now.Date.Year + ".txt";
                if (!System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
                {
                    System.IO.File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
                }
                using (System.IO.StreamWriter w = System.IO.File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
                {
                    w.WriteLine("\r\nLog Entry : ");
                    w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                    string err = "Error ID: " +ID+"   Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
                                  ". Error Message:" + errorMessage;
                    w.WriteLine(err);
                    w.WriteLine("__________________________");
                    w.Flush();
                    w.Close();
                }
            }
            catch (Exception ex)
            {
                WriteError(ex.Message, Path);
            }

        }
    }
}
